<template>
    <el-drawer :title="mode == 'view' ? '查看题目' : title" :visible="open" direction="rtl" :size="960" append-to-body @close="onClose">
      <div class="drawer-body">
        <div class="form-label">题型</div>
        <div class="question-type">
          <label>一级题型</label>
          <el-radio-group v-model="form.firstLevelType" :disabled="mode == 'view'">
            <el-radio-button v-for="item in firstLevelTypeOps" :key="item.value" :label="item.value">{{item.label}}</el-radio-button>
          </el-radio-group>
        </div>
        <div class="question-type">
          <label v-if="secondLevelTypeOps.length > 0">二级题型</label>
          <el-radio-group v-model="form.secondLevelType" :disabled="mode == 'view'" @input="onSecondTypeChange">
            <el-radio-button v-for="item in secondLevelTypeOps" :key="item.value" :label="item.value">{{item.label}}</el-radio-button>
          </el-radio-group>
        </div>
        <div v-if="form.formCode">
          <complex v-if="form.formCode == 'Assembly'" :readOnly="mode == 'view'" :initialVals="form" :clean="cleanInner" :validate="validate" @onChange="submitForm" />
          <basic v-else :initialVals="form" :readOnly="mode == 'view'" :clean="cleanInner" :validate="validate" @onChange="submitForm" />
        </div>
      </div>
      <div class="drawer-footer">
        <el-button v-if="mode != 'view'" type="primary" @click="triggerValidate">保存试题</el-button>
        <el-button @click="onClose">关 闭</el-button>
      </div>
    </el-drawer>
  </template>
  
  <script>
  import { getQuestionTypeList } from '@/api/publicManage/questionBase';
  import { addQuestion, updateQuestion } from '@/api/publicManage/questionBase';
  import Basic from './basic.vue';
  import Complex from './complex.vue';
  
  export default {
    name: "QuestionDrawer",
    props: {
      open: {
        type: Boolean,
        default: false,
      },
      mode: {
        type: String,
        default: 'edit'
      },
      libId: {
        type: Number,
        default: 0,
      },
      initData: {
        type: Object,
        default: () => ({}),
      }
    },
    components: { Basic, Complex },
    data() {
      return {
        title: "新增题目",
        firstLevelTypeOps: [],
        secondLevelTypeOps: [],
        form: {},
        validate: '',
        cleanInner: ''
      }
    },
    watch: {
      initData: {
        handler(val) {
          if (val.id) {
            let formData = { ...this.form, ...val };
            let temp = {};
            const { definition, answer, analysis } = formData.questionDetail || {};
            formData.difficulty = String(val.difficulty);
            if (formData.formCode === "Assembly") {
              const { descrips, items } = JSON.parse(definition);
              temp.descrips = descrips;
              temp.items = items.map((item, index) => ({ ...item, answer: JSON.parse(answer).items[index] }));
            } else {
              if (definition) temp = JSON.parse(definition);
              if (answer) temp.answer = JSON.parse(answer);
            }
            if (analysis) temp.analysis = analysis;
            if (Object.keys(temp).length > 0) {
              formData = { ...formData, ...temp };
              delete formData.questionDetail;
            }
            this.form = formData;
            this.title = '编辑题目';
          }
        }
      },
      'form.firstLevelType': {
        handler(val) {
          if (val) {
            const params = { typeLevel: 2, parentId: val };
            getQuestionTypeList(params).then(({ code, data }) => {
              if (code === 200) {
                this.secondLevelTypeOps = data.map(item => ({
                  label: item.name,
                  value: item.id,
                  formCode: item.formCode,
                }));
              }
            });
          }
        }
      }
    },
    created() {
      this.fetchFirstTypeList()
    },
    methods: {
      fetchFirstTypeList() {
        const params = { typeLevel: 1 };
        getQuestionTypeList(params).then(({ code, data }) => {
          if (code === 200) {
            this.firstLevelTypeOps = data.map(item => ({ label: item.name, value: item.id }));
          }
        })
      },
      onSecondTypeChange(val) {
        const result = this.secondLevelTypeOps.find(item => item.value === val);
        if (result) {
          this.form = { ...this.form, formCode: result.formCode };
          this.triggerClean();
        }
      },
      onClose() {
        this.form = {};
        this.secondLevelTypeOps = [];
        this.$emit('update:open', false);
      },
      filterObjShallow(obj) {
        const result = {};
        Object.keys(obj).map(item => {
          if (!['', null, undefined].includes(obj[item])) {
            result[item] = obj[item];
          }
        });
        return result;
      },
      // 清空内层表单
      triggerClean() {
        this.cleanInner = String(Date.now());
      },
      // 内层表单校验结果
      handleValid(isValid) {
        console.log(isValid);
      },
      // 触发表单验证
      triggerValidate() {
        this.validate = String(Date.now());
      },
      // 表单提交
      submitForm(data) {
        const formData = this.filterObjShallow(data);
        formData.libId = this.libId;
        formData.difficulty = data.difficulty * 1;
        formData.questionDetail = {};
        const definition = {};
        if (data.descrips) {
          definition.descrips = data.descrips;
          delete formData.descrips;
        }
        if (data.options) {
          definition.options = data.options;
          delete formData.options;
        }
        if (data.options1) {
          definition.options1 = data.options1;
          delete formData.options1;
        }
        if (data.options2) {
          definition.options2 = data.options2;
          delete formData.options2;
        }
        if (data.items) {
          const items = [];
          definition.items = data.items.map(item => {
            items.push(JSON.parse(JSON.stringify(item.answer)));
            delete item.answer;
            return item;
          });
          data.answer = { items };
          delete formData.items;
        }
        if (Object.keys(definition).length > 0) {
          formData.questionDetail.definition = JSON.stringify(definition);
        }
        if (data.answer) {
          formData.questionDetail.answer = JSON.stringify(data.answer);
          delete formData.answer;
        }
        if (data.analysis) {
          formData.questionDetail.analysis = data.analysis;
          delete formData.analysis;
        }
        let submitFunc = addQuestion;
        if (formData.id) submitFunc = updateQuestion;
        this.$emit('onOk', { formData, submitFunc });
        this.form = {};
        this.secondLevelTypeOps = [];
      },
    }
  }
  </script>
  
  <style lang="scss" scoped>
  @import './index.scss';
  </style>
  